/**
 * 图像处理工具函数集合
 */

/**
 * 将BASE64编码的图像数据转换为Blob对象
 * @param {string} base64Data BASE64编码的图像数据
 * @param {string} contentType 图像类型，默认为image/png
 * @returns {Blob} 图像的Blob对象
 */
export function base64ToBlob(base64Data, contentType = 'image/png') {
    const byteString = atob(base64Data.split(',')[1]);
    const mimeString = base64Data.split(',')[0].split(':')[1].split(';')[0];
    const ab = new ArrayBuffer(byteString.length);
    const ia = new Uint8Array(ab);

    for (let i = 0; i < byteString.length; i++) {
        ia[i] = byteString.charCodeAt(i);
    }

    return new Blob([ab], { type: contentType || mimeString });
}

/**
 * 调整图像大小
 * @param {HTMLImageElement} img 图像元素
 * @param {number} maxWidth 最大宽度
 * @param {number} maxHeight 最大高度
 * @returns {Object} 调整后的尺寸 {width, height}
 */
export function resizeImage(img, maxWidth, maxHeight) {
    let width = img.width;
    let height = img.height;

    // 计算缩放比例
    if (width > maxWidth || height > maxHeight) {
        const ratioWidth = maxWidth / width;
        const ratioHeight = maxHeight / height;
        const ratio = Math.min(ratioWidth, ratioHeight);

        width = width * ratio;
        height = height * ratio;
    }

    return { width, height };
}

/**
 * 将图像转换为Data URL
 * @param {File} file 图像文件
 * @returns {Promise<string>} 返回Data URL
 */
export function fileToDataURL(file) {
    return new Promise((resolve, reject) => {
        const reader = new FileReader();
        reader.onload = (e) => resolve(e.target.result);
        reader.onerror = reject;
        reader.readAsDataURL(file);
    });
}

/**
 * 从Data URL加载图像
 * @param {string} dataURL 图像的Data URL
 * @returns {Promise<HTMLImageElement>} 返回加载的图像元素
 */
export function loadImageFromDataURL(dataURL) {
    return new Promise((resolve, reject) => {
        const img = new Image();
        img.onload = () => resolve(img);
        img.onerror = reject;
        img.src = dataURL;
    });
}

/**
 * 获取图像的主要颜色
 * @param {HTMLImageElement} img 图像元素
 * @param {number} sampleSize 采样大小
 * @returns {string} 十六进制颜色代码
 */
export function getDominantColor(img, sampleSize = 5) {
    const canvas = document.createElement('canvas');
    const ctx = canvas.getContext('2d');
    canvas.width = sampleSize;
    canvas.height = sampleSize;

    ctx.drawImage(img, 0, 0, sampleSize, sampleSize);
    const imageData = ctx.getImageData(0, 0, sampleSize, sampleSize).data;

    let r = 0, g = 0, b = 0;
    const totalPixels = sampleSize * sampleSize;

    for (let i = 0; i < imageData.length; i += 4) {
        r += imageData[i];
        g += imageData[i + 1];
        b += imageData[i + 2];
    }

    r = Math.floor(r / totalPixels);
    g = Math.floor(g / totalPixels);
    b = Math.floor(b / totalPixels);

    return `#${(1 << 24 | r << 16 | g << 8 | b).toString(16).slice(1)}`;
}

/**
 * 将图像转换为指定格式
 * @param {string} dataURL 图像的Data URL
 * @param {string} format 输出格式 (默认为'image/png')
 * @param {number} quality 输出质量 0-1 (默认为0.9)
 * @returns {Promise<string>} 转换后的Data URL
 */
export function convertImageFormat(dataURL, format = 'image/png', quality = 0.9) {
    return new Promise((resolve, reject) => {
        const img = new Image();
        img.onload = () => {
            const canvas = document.createElement('canvas');
            canvas.width = img.width;
            canvas.height = img.height;

            const ctx = canvas.getContext('2d');
            ctx.drawImage(img, 0, 0);

            resolve(canvas.toDataURL(format, quality));
        };
        img.onerror = reject;
        img.src = dataURL;
    });
}
